import React, { forwardRef, useImperativeHandle, useState } from "react"
import { Modal as AntdModal } from 'antd'
import { CommonComponentProps } from "../../interface"

export interface ModalRef {
  open: () => void
  close: () => void
}

const Modal: React.ForwardRefRenderFunction<ModalRef, Omit<CommonComponentProps, 'id' | 'name'>> = ({children, title, onOk, onCancel, styles}, ref) => {

  const [open, setOpen] = useState(false)

  useImperativeHandle(ref, () => {
    return {
      open: () => {
        setOpen(true)
      },
      close: () => {
        setOpen(false)
      }
    }
  }, [])

  return <AntdModal
  title={title}
  style={styles}
  open={open}
  onCancel={() => {
    if (onCancel) {
      onCancel();
    }
    setOpen(false)
  }}
  onOk={() => {
    if (onOk) {
      onOk();
    }
  }}
  destroyOnClose
  >
    {children}
  </AntdModal>
}

export default forwardRef(Modal)